<template>
  <div class="crm-workbench">
    <div class="d-flex">
      <!-- 线索统计 -->
      <div class="leads-statistics flex-1">
        <div class="b-top d-flex justify-content-between align-items-center">
          <span class="title-top"
            >线索统计
            <el-tooltip
              class="item"
              effect="dark"
              content="按照表单获取时间统计线索的总数、转化数量、未转化数量"
              placement="top-start"
            >
              <i class="el-icon-question"></i>
            </el-tooltip>
          </span>
          <div class="d-flex align-items-center">
            <el-select
              v-model="leadsForm.label"
              placeholder="请选择"
              style="width: 110px;height:32px;"
              class="mr-10"
            >
              <el-option label="销售负责人" :value="1"> </el-option>
              <el-option label="线索负责人" :value="2"> </el-option>
            </el-select>
            <!-- 部门 -->
            <manage-dep
              class="mr-10"
              style="width:100px;height:32px;overflow:hidden;"
              @submitDeps="manageDepSave($event, 'leadsForm')"
              :manageDeptId="leadsForm.deptIdArray"
              :showIpt="true"
              :visible="false"
              :isShowName="true"
            />
            <!-- 人员 -->
            <relate-empoyee
              style="width:100px;overflow:hidden;"
              :visible="false"
              :show-input="true"
              :isShowName="true"
              :user-id="leadsForm.userArray"
              ref="relate_empoyee"
              @save="employeesSave($event, 'leadsForm')"
            />
            <el-date-picker
              class="mr-10"
              v-model="leadsForm.dateTime"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
              value-format="yyyy-MM-dd"
              :size="'small'"
              style="width: 240px; margin-left: 12px"
              :clearable="false"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
            <el-button
              type="primary"
              icon="el-icon-search"
              class="company-search"
              @click="searchData('leads')"
              >搜索</el-button
            >
          </div>
        </div>
        <div class="b-count d-flex justify-content-between">
          <div
            class="count-info"
            v-for="(item, index) in leadsList"
            :key="index"
            :style="{ 'background-image': 'url(' + item.imgName + ')' }"
          >
            <div class="count-top d-flex align-items-center">
              <img :src="item.iconName" alt="" />
              <span
                class="ml-10 color-03 size-14"
                :style="{ color: item.color }"
                >{{ item.label }}</span
              >
            </div>
            <span class="count" :style="{ color: item.color }">{{
              resLeadsData[item.count] || 0
            }}</span>
          </div>
        </div>
      </div>
      <!-- 学员合同统计 -->
      <div class="customer-statistics flex-1">
        <div class="b-top d-flex justify-content-between align-items-center">
          <span class="title-top">学员及合同统计</span>
          <div class="d-flex align-items-center">
            <el-select
              v-model="customerForm.label"
              placeholder="请选择"
              style="width: 110px;height:32px;"
              class="mr-10"
            >
              <el-option label="销售负责人" :value="1"> </el-option>
              <el-option label="线索负责人" :value="2"> </el-option>
            </el-select>
            <!-- 部门 -->
            <manage-dep
              class="mr-10"
              style="width: 100px;height:32px;"
              @submitDeps="manageDepSave($event, 'customerForm')"
              :manageDeptId="customerForm.deptIdArray"
              :showIpt="true"
              :visible="false"
              :isShowName="true"
            />
            <!-- 人员 -->
            <relate-empoyee
              style="width: 100px;"
              :visible="false"
              :show-input="true"
              :isShowName="true"
              :user-id="customerForm.userArray"
              ref="relate_empoyee"
              @save="employeesSave($event, 'customerForm')"
            />
            <el-date-picker
              class="mr-10"
              v-model="customerForm.dateTime"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
              value-format="yyyy-MM-dd"
              :size="'small'"
              style="width: 240px; margin-left: 12px"
              :clearable="false"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
            <el-button
              type="primary"
              icon="el-icon-search"
              class="company-search"
              @click="searchData('customer')"
              >搜索</el-button
            >
          </div>
        </div>
        <div class="b-count d-flex justify-content-between">
          <div
            class="count-info"
            v-for="(item, index) in customerList"
            :key="index"
            :style="{ 'background-image': 'url(' + item.imgName + ')' }"
          >
            <div class="count-top d-flex align-items-center">
              <img :src="item.iconName" alt="" />
              <span
                class="ml-10 color-03 size-14"
                :style="{ color: item.color }"
                >{{ item.label }}
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="item.tooltip"
                  placement="top-start"
                >
                  <i class="el-icon-question"></i> </el-tooltip
              ></span>
            </div>
            <span class="count" :style="{ color: item.color }">{{
              resCustomerData[item.count] || 0
            }}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="d-flex">
      <!-- 金额统计 -->
      <div class="money-statistics flex-1">
        <div class="b-top d-flex justify-content-between align-items-center">
          <span class="title-top">金额统计</span>
          <div class="d-flex align-items-center">
            <!-- 部门 -->
            <manage-dep
              class="mr-10"
              style="width: 100px;height:32px;"
              @submitDeps="manageDepSave($event, 'moneyForm')"
              :manageDeptId="moneyForm.deptIdArray"
              :showIpt="true"
              :visible="false"
              :isShowName="true"
            />
            <!-- 人员 -->
            <relate-empoyee
              style="width: 100px;"
              :visible="false"
              :show-input="true"
              :isShowName="true"
              :user-id="moneyForm.userArray"
              ref="relate_empoyee"
              @save="employeesSave($event, 'moneyForm')"
            />
            <el-date-picker
              class="mr-10"
              v-model="moneyForm.dateTime"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
              value-format="yyyy-MM-dd"
              :size="'small'"
              style="width: 240px; margin-left: 12px"
              :clearable="false"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
            <el-button
              type="primary"
              icon="el-icon-search"
              class="company-search"
              @click="searchData('money')"
              >搜索</el-button
            >
          </div>
        </div>
        <div class="b-count d-flex flex-wrap">
          <div
            class="count-info d-flex flex-column"
            v-for="(item, index) in moneyList"
            :key="index"
          >
            <span class="color-03 size-14"
              >{{ item.label }}
              <el-tooltip
                class="item"
                effect="dark"
                :content="item.tooltip"
                placement="top-start"
              >
                <i class="el-icon-question"></i> </el-tooltip
            ></span>
            <span class="count mt-10 xr-money" :style="{ color: item.color }">{{
              resMoneyData[item.money] || 0
            }}</span>
          </div>
        </div>
      </div>
      <!-- 销售排行 -->
      <div class="sale-ranking flex-1">
        <div class="b-top d-flex justify-content-between align-items-center">
          <span class="title-top"
            >销售统计
            <el-tooltip
              class="item"
              effect="dark"
              content="按照合同金额、回款金额统计销售排行数据"
              placement="top-start"
            >
              <i class="el-icon-question"></i>
            </el-tooltip>
          </span>
          <div class="d-flex align-items-center">
            <el-select
              v-model="saleForm.label"
              placeholder="请选择"
              style="width: 100px;height:32px;"
              class="mr-10"
            >
              <el-option label="合同金额" :value="6"> </el-option>
              <el-option label="回款金额" :value="7"> </el-option>
            </el-select>
            <!-- 部门 -->
            <manage-dep
              class="mr-10"
              style="width: 100px;height:32px;"
              @submitDeps="manageDepSave($event, 'saleForm')"
              :manageDeptId="saleForm.deptIdArray"
              :showIpt="true"
              :visible="false"
              :isShowName="true"
            />
            <!-- 人员 -->
            <relate-empoyee
              style="width: 100px;"
              :visible="false"
              :show-input="true"
              :isShowName="true"
              :user-id="saleForm.userArray"
              ref="relate_empoyee"
              @save="employeesSave($event, 'saleForm')"
            />
            <el-date-picker
              class="mr-10"
              v-model="saleForm.dateTime"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
              value-format="yyyy-MM-dd"
              :size="'small'"
              style="width: 240px; margin-left: 12px"
              :clearable="false"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
            <el-button
              type="primary"
              icon="el-icon-search"
              class="company-search"
              @click="searchData('sale')"
              >搜索</el-button
            >
          </div>
        </div>
        <div class="b-count">
          <el-table :data="resSaleData" style="width: 100%;height:100%;">
            <template slot="empty">
              <el-empty
                :image="require('../../../assets/img/crm/empty_not.png')"
                :image-size="256"
                description="暂无数据"
              ></el-empty>
            </template>
            <el-table-column prop="index" label="排名" align="left">
              <template slot-scope="scope">
                <span v-if="scope.row.index > 3" class="level-index">{{
                  scope.row.index
                }}</span>
                <!-- 前三展示图片 -->
                <img
                  v-else
                  class="level-img"
                  :src="
                    require('../../../assets/img/crm/workbench/level' +
                      scope.row.index +
                      '.png')
                  "
                />
              </template>
            </el-table-column>
            <el-table-column prop="realName" label="姓名" align="center">
            </el-table-column>
            <el-table-column prop="money" label="回款金额" align="center">
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <!-- 最新公告提醒 -->
    <notice-flow-update-dialog
      :visible.sync="NoticeFlowUpdateDialogShow"
      :details="noticeDetails"
    >
    </notice-flow-update-dialog>
  </div>
</template>

<script>
import RelateEmpoyee from "./components/RelateEmpoyee.vue"; // 人员选择器
import ManageDep from "./components/manageDep.vue"; // 部门选择器
import NoticeFlowUpdateDialog from "./components/NoticeFlowUpdateDialog";
import {
  getLeadsStatis,
  getNumStatis,
  getMoneyStatis,
  getRankStatis,
  getNewNotice
} from "@/api/crm/workbench";
export default {
  name: "Workbench",
  components: {
    RelateEmpoyee,
    ManageDep,
    NoticeFlowUpdateDialog
  },
  data() {
    return {
      NoticeFlowUpdateDialogShow: false,
      noticeDetails: {},
      // 线索统计搜索
      leadsForm: {
        dateTime: "",
        startTime: null,
        endTime: null,
        userArray: [],
        deptIdArray: [],
        label: 1
      },
      // 学员统计搜索
      customerForm: {
        dateTime: "",
        startTime: null,
        endTime: null,
        userArray: [],
        deptIdArray: [],
        label: 1
      },
      // 销售统计搜索
      saleForm: {
        dateTime: "",
        startTime: null,
        endTime: null,
        userArray: [],
        deptIdArray: []
      },
      // 金额统计搜索
      moneyForm: {
        dateTime: "",
        startTime: null,
        endTime: null,
        userArray: [],
        deptIdArray: []
      },

      // 线索数据
      leadsList: [
        {
          imgName: require("../../../assets/img/crm/workbench/leadsNum-bj.png"),
          iconName: require("../../../assets/img/crm/workbench/leadsNum.png"),
          label: " 线索总数",
          count: "leadsNum",
          color: "#0166FF"
        },
        {
          imgName: require("../../../assets/img/crm/workbench/transformNum-bj.png"),
          iconName: require("../../../assets/img/crm/workbench/transformNum.png"),
          label: "已转化数量",
          count: "leadsNumTransform",
          color: "#64CF97"
        },
        {
          imgName: require("../../../assets/img/crm/workbench/notLeadsNum-bj.png"),
          iconName: require("../../../assets/img/crm/workbench/notLeadsNum.png"),
          label: "未转化数量",
          count: "leadsNumNOTransform",
          color: "#FCC549"
        }
      ],
      // 学员数据
      customerList: [
        {
          imgName: require("../../../assets/img/crm/workbench/studentNum-bj.png"),
          iconName: require("../../../assets/img/crm/workbench/studentNum.png"),
          label: "学员总数",
          count: "studentNum",
          color: "#0166FF",
          tooltip: "按照创建时间统计学员总数"
        },
        {
          imgName: require("../../../assets/img/crm/workbench/vipStudentNum-bj.png"),
          iconName: require("../../../assets/img/crm/workbench/vipStudentNum.png"),
          label: "VIP学员总数",
          count: "vipStudentNum",
          color: "#FC784C",
          tooltip: "按照创建时间统计vip学员总数"
        },
        {
          imgName: require("../../../assets/img/crm/workbench/contractNum-bj.png"),
          iconName: require("../../../assets/img/crm/workbench/contractNum.png"),
          label: "合同总数",
          count: "contractNum",
          color: "#49C988",
          tooltip: "按照成交时间/审核通过时间统计合同总数"
        }
      ],
      // 学员接口数据
      resCustomerData: {},
      // 线索接口数据
      resLeadsData: {},
      // 销售数据
      saleList: [],
      // 销售接口数据
      resSaleData: [],
      // 金额统计
      moneyList: [
        {
          label: "合同金额（元）",
          money: "contractMoney",
          value: "",
          tooltip: "统计所有类别审核通过的合同总金额"
        },
        {
          label: "首付款回款金额（元）",
          money: "firstReceivablesMoney",
          value: "",
          tooltip: "统计审核通过的首付款回款金额"
        },
        {
          label: "账单回款金额（元）",
          money: "orderMoney",
          value: "",
          tooltip: "统计账单审核通过的回款金额"
        },
        {
          label: "现金回款金额（元）",
          money: "receivablesMoney",
          value: "",
          tooltip: "统计现金审核通过的回款金额"
        },
        {
          label: "线下补款回款金额（元）",
          money: "offlineMoney",
          value: "",
          tooltip: "统计线下补款审核通过的回款金额"
        },
        {
          label: "退款金额（元）",
          money: "refundMoney",
          value: "",
          tooltip: "统计退款审核通过的金额总数"
        }
      ],
      // 金额统计接口数据
      resMoneyData: {},

      pickerMinDate: "",
      pickerOptions: {
        onPick: ({ maxDate, minDate }) => {
          this.pickerMinDate = minDate.getTime();
          if (maxDate) this.pickerMinDate = "";
        },
        disabledDate: time => {
          if (this.pickerMinDate !== "") {
            const one = 60 * 24 * 3600 * 1000;
            const minTime = this.pickerMinDate - one;
            const maxTime = this.pickerMinDate + one;
            return time.getTime() < minTime || time.getTime() > maxTime;
          }
        }
      }
    };
  },
  created() {
    // 初始化时间
    this.initDate();
    // 数据初始化
    this.initData();
    getNewNotice().then(res => {
      if (res) {
        const noticeId = localStorage.getItem("noticeId"); // 获取存储的公告id
        if (noticeId == res.data.id) {
          // 如果公告id一致不展示弹框
        } else {
          this.noticeDetails = res.data;
          this.NoticeFlowUpdateDialogShow = true;
          localStorage.setItem("noticeId", res.data.id);
        }
      }
    });
  },
  mounted() {
    document.addEventListener("visibilitychange", this.visibilityState); //监听页面显隐
  },
  beforeDestroy() {
    document.removeEventListener("visibilitychange", this.visibilityState); //移除监听
  },

  methods: {
    initDate() {
      const startTime = this.$moment(new Date()).format("YYYY-MM") + "-01";
      const endTime = this.$moment(new Date()).format("YYYY-MM-DD");
      // 学员
      Object.assign(this.leadsForm, {
        startTime,
        endTime,
        dateTime: [startTime, endTime]
      });
      // 线索
      Object.assign(this.customerForm, {
        startTime,
        endTime,
        dateTime: [startTime, endTime]
      });
      // 金额
      Object.assign(this.moneyForm, {
        startTime,
        endTime,
        dateTime: [startTime, endTime]
      });
      // 销售
      Object.assign(this.saleForm, {
        startTime,
        endTime,
        dateTime: [startTime, endTime]
      });
    },
    initData() {
      this.searchData("leads");
      this.searchData("customer");
      this.searchData("money");
      this.searchData("sale");
    },
    // 搜索
    searchData(type) {
      if (this[`${type}Form`].dateTime) {
        this[`${type}Form`].startTime =
          this[`${type}Form`].dateTime[0] + " 00:00:00";
        this[`${type}Form`].endTime =
          this[`${type}Form`].dateTime[1] + " 23:59:59";
      }
      switch (type) {
        case "leads":
          this.getLeadsStatis();
          break;
        case "customer":
          this.getNumStatis();
          break;
        case "money":
          this.getMoneyStatis();
          break;
        case "sale":
          this.getRankStatis();
      }
    },

    // 线索搜索
    async getLeadsStatis() {
      const res = await getLeadsStatis({
        deptIdArray: this.leadsForm.deptIdArray,
        userArray: this.leadsForm.userArray,
        startTime: this.leadsForm.startTime,
        endTime: this.leadsForm.endTime,
        statisType: this.leadsForm.label
      });
      if (res && res.code == 0) {
        this.resLeadsData = res.data;
      }
    },
    // 金额统计
    async getMoneyStatis() {
      const res = await getMoneyStatis({
        deptIdArray: this.moneyForm.deptIdArray,
        userArray: this.moneyForm.userArray,
        startTime: this.moneyForm.startTime,
        endTime: this.moneyForm.endTime
      });
      if (res && res.code == 0) {
        this.resMoneyData = res.data;
      }
    },
    // 学员搜索
    async getNumStatis() {
      const res = await getNumStatis({
        deptIdArray: this.customerForm.deptIdArray,
        userArray: this.customerForm.userArray,
        startTime: this.customerForm.startTime,
        endTime: this.customerForm.endTime,
        statisType: this.customerForm.label
      });
      if (res && res.code == 0) {
        this.resCustomerData = res.data;
      }
    },
    // 销售排行
    async getRankStatis() {
      const res = await getRankStatis({
        deptIdArray: this.saleForm.deptIdArray,
        userArray: this.saleForm.userArray,
        startTime: this.saleForm.startTime,
        endTime: this.saleForm.endTime,
        label: this.saleForm.label
      });
      if (res && res.code == 0) {
        this.resSaleData = res.data;
        this.resSaleData.forEach((item, index) => {
          item.index = index + 1;
        });
      }
    },

    /**
     * 员工选择
     */
    employeesSave(e, name) {
      this[name].userArray = e;
    },

    /**
     * 部门选择
     */
    manageDepSave(e, name) {
      this[name].deptIdArray = e.split(",")[0] === "" ? [] : e.split(",");
    },

    visibilityState(e) {
      let visibilityState = e.target.visibilityState;
      switch (visibilityState) {
        case "visible": //显示
          break;
        case "hidden": //隐藏
          break;
        default:
      }
    }
  }
};
</script>

<style scoped lang="scss">
@import "./workbench.scss";
</style>
